package cn.wolfcode.util;

import cn.wolfcode.qo.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;

/*
* 对控制器进行增强
* handlerMethod出现异常时那个方法
* */

@ControllerAdvice
public class ControllerExceptionCatch {

    @ExceptionHandler(RuntimeException.class)//运行时的异常
    public Object handler(RuntimeException e, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception {
        e.printStackTrace();
        //判断是异步请求异常还是其他
        if(handlerMethod.hasMethodAnnotation(ResponseBody.class)){
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(new JsonResult(false,"操作失败")));
            return null;
        }else{
            return "common/error";
        }

    }

}




